import { ref } from 'vue'
import { defineStore } from 'pinia'
import router from '@/router' // ✅ 引入路由实例

export const useUserStore = defineStore(
  'user',
  () => {
    const userInfo = ref({
      id: 0,
      username: '',
      email: '',
    })

    const setUserInfo = (info: any) => {
      userInfo.value = info
      localStorage.setItem('userInfo', JSON.stringify(info))
    }

    const clearUserInfo = () => {
      // 清除用户信息
      userInfo.value = {
        id: 0,
        username: '',
        email: '',
      }
      localStorage.removeItem('userInfo')
      // 清除 token
      localStorage.removeItem('token')
      router.replace('/login')
    }

    return {
      userInfo,
      setUserInfo,
      clearUserInfo,
    }
  },
  {
    persist: true,
  },
)
